#define _LPTIM_C_
/* Includes ---------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "lptim.h"
/* USER CODE END Includes */

/* Types ------------------------------------------------------------*/
/* USER CODE BEGIN Types */

/* USER CODE END Types */

/* Constants --------------------------------------------------------*/
/* USER CODE BEGIN Constants */

/* USER CODE END Constants */

/* Macro ------------------------------------------------------------*/
/* USER CODE BEGIN Macro */

/* USER CODE END Macro */

/* Variables ---------------------------------------------------------*/
/* USER CODE BEGIN Variables */
uint8_t gucUart0RxTimer = 0;
uint8_t gucUart4RxTimer = 0;
/* USER CODE END Variables */

/* Function prototypes -----------------------------------------------*/
/* USER CODE BEGIN FP */
static void vLPTIM32TimerBaseInit(void);
static void vLPTIM32Setup(void);
/* USER CODE END FP */

void vLPTIMInit(void)
{
	vLPTIM32TimerBaseInit();
	vLPTIM32Setup();
}

static void vLPTIM32TimerBaseInit(void)
{
	FL_NVIC_ConfigTypeDef InterruptConfigStruct;
	FL_LPTIM32_InitTypeDef TimerBase_InitStruct;

    TimerBase_InitStruct.clockSource = FL_CMU_LPTIM32_CLK_SOURCE_APBCLK;
    TimerBase_InitStruct.prescalerClockSource = FL_LPTIM32_CLK_SOURCE_INTERNAL;
    TimerBase_InitStruct.prescaler = FL_LPTIM32_PSC_DIV1;
	
	// clock:1MHz,1000->1ms; clock:32KHz,32->1ms
#if(SystemClock == CLK_SOURCE_RCLP_32K)
    TimerBase_InitStruct.autoReload = 640; // 20ms 
#elif(SystemClock == CLK_SOURCE_XTHF_1MHz)
	TimerBase_InitStruct.autoReload = 20000; // 20ms
#endif
    TimerBase_InitStruct.mode = FL_LPTIM32_OPERATION_MODE_NORMAL;
    TimerBase_InitStruct.onePulseMode = FL_LPTIM32_ONE_PULSE_MODE_CONTINUOUS;
    TimerBase_InitStruct.triggerEdge = FL_LPTIM32_ETR_TRIGGER_EDGE_RISING;
    TimerBase_InitStruct.countEdge = FL_LPTIM32_ETR_COUNT_EDGE_RISING;

    FL_LPTIM32_Init(LPTIM32, &TimerBase_InitStruct);
	
	FL_LPTIM32_ClearFlag_Update(LPTIM32);
    FL_LPTIM32_EnableIT_Update(LPTIM32);

    InterruptConfigStruct.preemptPriority = 0x03;
    FL_NVIC_Init(&InterruptConfigStruct, LPTIMx_IRQn);
}

static void vLPTIM32Setup(void)
{
    FL_LPTIM32_Enable(LPTIM32);
}

void LPTIM_IRQHandler(void)
{
    if(FL_LPTIM32_IsEnabledIT_Update(LPTIM32) && FL_LPTIM32_IsActiveFlag_Update(LPTIM32))
    {
        FL_LPTIM32_ClearFlag_Update(LPTIM32);
		
		//FL_GPIO_ToggleOutputPin(GPIOA, FL_GPIO_PIN_12);
		
		if(GET_UART0_HART_RX_START_FLG())
		{
			gucUart0RxTimer++;
			if(gucUart0RxTimer >= 5) // 20ms*12=240ms
			{
				CLR_UART0_HART_RX_START_FLG();
				SET_UART0_HART_RX_FINISHED_FLG();
			}
		}
		
		if(GET_UART4_RX_START_FLG())
		{
			gucUart4RxTimer++;
			if(gucUart4RxTimer >= 3) // 20ms*3=60ms
			{
				CLR_UART4_RX_START_FLG();
				SET_UART4_RX_FINISHED_FLG();
			}
		}
    }
}
